// 练习历史记录页面交互功能
document.addEventListener('DOMContentLoaded', function() {
    // 初始化筛选功能
    initFilterFunctionality();

    // 初始化表格排序
    initTableSorting();

    // 绑定清除筛选功能
    bindClearFilters();

    // 初始化统计计算
    calculatePracticeStats();

    // 绑定导出功能
    bindExportFunctionality();
});

// 初始化筛选功能
function initFilterFunctionality() {
    const filterForm = document.getElementById('practiceFilterForm');
    const filterInputs = filterForm.querySelectorAll('select, input');

    // 输入变化时自动提交表单
    filterInputs.forEach(input => {
        input.addEventListener('change', function() {
            // 添加防抖，避免频繁提交
            clearTimeout(this.debounceTimer);
            this.debounceTimer = setTimeout(() => {
                filterForm.submit();
            }, 500);
        });
    });
}

// 初始化表格排序
function initTableSorting() {
    const tableHeaders = document.querySelectorAll('.practice-table th[data-sort]');

    tableHeaders.forEach(header => {
        header.style.cursor = 'pointer';

        header.addEventListener('click', function() {
            const sortBy = this.dataset.sort;
            const currentOrder = this.dataset.order || 'desc';
            const newOrder = currentOrder === 'desc' ? 'asc' : 'desc';

            // 更新排序指示器
            updateSortIndicator(this, newOrder);

            // 执行排序
            sortTable(sortBy, newOrder);
        });
    });
}

// 更新排序指示器
function updateSortIndicator(header, order) {
    // 清除所有排序指示器
    document.querySelectorAll('.practice-table th').forEach(th => {
        th.classList.remove('sort-asc', 'sort-desc');
        th.dataset.order = '';
    });

    // 设置当前排序
    header.classList.add(`sort-${order}`);
    header.dataset.order = order;
}

// 表格排序
function sortTable(sortBy, order) {
    const table = document.querySelector('.practice-table');
    const tbody = table.querySelector('tbody');
    const rows = Array.from(tbody.querySelectorAll('tr'));

    rows.sort((a, b) => {
        let aValue, bValue;

        switch (sortBy) {
            case 'date':
                aValue = new Date(a.cells[0].textContent);
                bValue = new Date(b.cells[0].textContent);
                break;
            case 'knowledge_point':
                aValue = a.cells[1].textContent.toLowerCase();
                bValue = b.cells[1].textContent.toLowerCase();
                break;
            case 'result':
                aValue = a.cells[2].textContent;
                bValue = b.cells[2].textContent;
                break;
            case 'score':
                aValue = parseFloat(a.cells[3].textContent) || 0;
                bValue = parseFloat(b.cells[3].textContent) || 0;
                break;
            default:
                return 0;
        }

        if (order === 'asc') {
            return aValue > bValue ? 1 : -1;
        } else {
            return aValue < bValue ? 1 : -1;
        }
    });

    // 重新插入排序后的行
    rows.forEach(row => tbody.appendChild(row));

    showNotification(`已按${getSortLabel(sortBy)}${order === 'asc' ? '升序' : '降序'}排序`, 'info');
}

// 获取排序标签
function getSortLabel(sortBy) {
    const labels = {
        'date': '练习时间',
        'knowledge_point': '知识点',
        'result': '结果',
        'score': '得分'
    };
    return labels[sortBy] || '默认';
}

// 绑定清除筛选功能
function bindClearFilters() {
    const clearBtn = document.getElementById('clearFilters');
    if (clearBtn) {
        clearBtn.addEventListener('click', function() {
            const url = new URL(window.location.href);
            url.search = '';
            window.location.href = url.toString();
        });
    }
}

// 计算练习统计
function calculatePracticeStats() {
    const tableRows = document.querySelectorAll('.practice-table tbody tr');

    if (tableRows.length === 0) return;

    let totalScore = 0;
    let correctCount = 0;
    let subjects = new Set();
    let knowledgePoints = new Set();

    tableRows.forEach(row => {
        const score = parseFloat(row.cells[3].textContent) || 0;
        const result = row.cells[2].textContent.trim();
        const subject = row.cells[4].textContent;
        const knowledgePoint = row.cells[1].textContent;

        totalScore += score;
        if (result === '正确') correctCount++;
        subjects.add(subject);
        knowledgePoints.add(knowledgePoint);
    });

    const avgScore = totalScore / tableRows.length;
    const accuracy = (correctCount / tableRows.length) * 100;

    // 更新统计显示
    updateStatDisplay('total-practices', tableRows.length);
    updateStatDisplay('avg-score', avgScore.toFixed(1));
    updateStatDisplay('accuracy', accuracy.toFixed(1) + '%');
    updateStatDisplay('subjects-covered', subjects.size);
    updateStatDisplay('knowledge-points', knowledgePoints.size);
}

// 更新统计显示
function updateStatDisplay(elementId, value) {
    const element = document.getElementById(elementId);
    if (element) {
        element.textContent = value;
    }
}

// 绑定导出功能
function bindExportFunctionality() {
    const exportBtn = document.getElementById('exportPracticeData');
    if (exportBtn) {
        exportBtn.addEventListener('click', exportPracticeData);
    }
}

// 导出练习数据
function exportPracticeData() {
    const tableRows = document.querySelectorAll('.practice-table tbody tr');
    const exportData = {
        exportTime: new Date().toISOString(),
        totalRecords: tableRows.length,
        practices: []
    };

    tableRows.forEach(row => {
        const practice = {
            date: row.cells[0].textContent,
            knowledgePoint: row.cells[1].textContent,
            result: row.cells[2].textContent,
            score: row.cells[3].textContent,
            subject: row.cells[4].textContent,
            exam: row.cells[5].textContent,
            notes: row.cells[6].textContent
        };
        exportData.practices.push(practice);
    });

    const dataStr = JSON.stringify(exportData, null, 2);
    const dataBlob = new Blob([dataStr], {type: 'application/json'});

    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `practice-history-${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    URL.revokeObjectURL(url);

    showNotification('练习历史数据导出成功！', 'success');
}

// 显示通知
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `alert alert-${type} alert-dismissible fade show`;
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
        min-width: 300px;
    `;
    notification.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;

    document.body.appendChild(notification);

    setTimeout(() => {
        if (notification.parentNode) {
            notification.parentNode.removeChild(notification);
        }
    }, 3000);
}

// 快速筛选功能
function initQuickFilters() {
    const quickFilterBtns = document.querySelectorAll('.quick-filter');
    quickFilterBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const filterType = this.dataset.filterType;
            const filterValue = this.dataset.filterValue;

            // 设置筛选值并提交表单
            const form = document.getElementById('practiceFilterForm');
            form.querySelector(`[name="${filterType}"]`).value = filterValue;
            form.submit();
        });
    });
}

// 初始化所有功能
function initializeAll() {
    initFilterFunctionality();
    initTableSorting();
    bindClearFilters();
    calculatePracticeStats();
    bindExportFunctionality();
    initQuickFilters();
}

// 页面加载完成后初始化
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initializeAll);
} else {
    initializeAll();
}